package net.zhengxinyun.performance.controller.department;

import com.mchange.v1.db.sql.ResultSetUtils;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.zhengxinyun.performance.core.Result;
import net.zhengxinyun.performance.core.ResultUtils;
import net.zhengxinyun.performance.entity.*;
import net.zhengxinyun.performance.filter.CountryUnitIndicatorsFilter;
import net.zhengxinyun.performance.filter.DepartClassFilter;
import net.zhengxinyun.performance.service.departClass.DepartClassItemService;
import net.zhengxinyun.performance.service.departClass.DepartClassService;
import net.zhengxinyun.performance.service.departClass.DepartHeadService;
import net.zhengxinyun.performance.service.indicators.CountryUnitIndicatorsService;
import net.zhengxinyun.performance.service.login.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/departclass")
public class DepartClassCtrl {




    private DepartClassService dpclassService;
    private TokenService tokenService;

    @Autowired
    private DepartClassItemService itemService;

    @Autowired
    private DepartHeadService headService;

    @Autowired
    private CountryUnitIndicatorsService uninService;


    @Autowired
    public DepartClassCtrl(DepartClassService dpclassService, TokenService tokenService) {
        this.dpclassService = dpclassService;
        this.tokenService = tokenService;
    }

    @PostMapping("/query")
    public Result<HashMap<String,Object>> query(@RequestBody DepartClassParam param)
    {
        if(tokenService.compareToken(param.tokenEntity.getValue()))
        {
            HashMap<String,Object> map = new HashMap<>();

            List<DepartClassFilter> list = dpclassService.query(param.departClassFilter);
            if(list.size()==0&& param.departClassFilter.getPageNumber()!=0)
            {
                param.departClassFilter.setPageNumber(param.departClassFilter.getPageNumber()-1);
            }
            list=dpclassService.query(param.departClassFilter);
            Integer pagetotal =dpclassService.queryForCount(param.departClassFilter);

            List<Map<String,Object>> dataList = new ArrayList<>();
            int i = 0;
            for (DepartClassFilter entity : list) {
                Map<String ,Object> dataMap = new LinkedHashMap<>();
                String cell ="cell";
                dataMap.put(cell+i,entity.getClassname()   );
                i++;
                dataMap.put(cell+i,entity.getDatetime());
                i++;
                List<DepartClassItem> items = itemService.queryByClassId(entity.getId());


                for (DepartClassItem item : items) {
                    dataMap.put(cell+i,item.getWeight());
                    i++;

                }


            }


            map.put("list",list);
            map.put("pageTotal",pagetotal);
            return ResultUtils.getSuccessResults(map);
        }
        return  ResultUtils.getResults(Result.Status.OVERTIME,"error token",null);
    }

    @PostMapping("/insert")
    public Result<String> insert(@RequestBody  DepartClassParam param){
        if (tokenService.compareToken(param.tokenEntity.getValue())){
            dpclassService.insert(param.departClassFilter);
            return ResultUtils.getSuccessResults();
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对");
    }


// 修改
    @PostMapping("/update")
    public Result<String> update(@RequestBody DepartClassParam param){
        if (tokenService.compareToken(param.tokenEntity.getValue())){
            dpclassService.update(param.departClassFilter);
            return ResultUtils.getSuccessResults();
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对");
    }
    //删除
    @PostMapping("/delete")
    public Result<String> delete(@RequestBody DepartClassParam param){
        if (tokenService.compareToken(param.tokenEntity.getValue())){
            String delete = dpclassService.delete(param.departClassFilter);
            return ResultUtils.getSuccessResults();
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对");
    }
    @GetMapping("/getDepartclass")
    public Result<HashMap<String,Object>> getdepartclass(@RequestBody DepartClassParam param){
        if (tokenService.compareToken(param.tokenEntity.getValue())){
            DepartClassFilter filter  = new DepartClassFilter();
            HashMap<String,Object> map = new HashMap<>();
            List<DepartClassFilter> list=dpclassService.query(filter);
            map.put("list",list);
            return ResultUtils.getSuccessResults(map);
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对",null);
    }

    //保存表头
    @PostMapping("/insertHead")
    public Result<String> insertHead(@RequestBody DepartClassParam param){
        if (tokenService.compareToken(param.tokenEntity.getValue())){

            List<DepartClassHead> list = param.departClassFilter.getItemList();
            String datetime = param.departClassFilter.getDatetime();
            list.stream().forEach(item -> item.setDatetime(datetime));

           int i = headService.saveItems(list);
           if(i==0)
           {
               return  ResultUtils.getResults(Result.Status.ERROR,"保存失败");
           }
            return ResultUtils.getSuccessResults();
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对",null);
    }

    //修改表头
    @PostMapping("/updateHead")
    public Result<String> updateHead(@RequestBody DepartClassParam param)
    {
        if (tokenService.compareToken(param.tokenEntity.getValue())){

            List<Long> delList = param.departClassFilter.getDelList();
            for (Long aLong : delList) {
                if(aLong.equals(new Long(1))
                ||aLong.equals(new Long(2)) ||aLong.equals(new Long(3)) ||aLong.equals(new Long(4))
                )
                {
                    continue;
                }

                headService.delete(aLong);
            }

            List<DepartClassHead> itemList = param.departClassFilter.getItemList();

            List<DepartClassHead> saveList  = new ArrayList<>();
            for (DepartClassHead head : itemList) {
                if(ObjectUtils.isBlank(head.getId()))
                {
                    head.setDatetime(param.departClassFilter.getDatetime());
                    saveList.add(head);
                }else

                headService.update(head);
            }
            if(saveList.size()>0)
            {
                headService.saveItems(saveList);
            }


            return ResultUtils.getSuccessResults();
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对",null);
    }

    //查询表头
    @PostMapping("/queryHead")
    public  Result<HashMap<String,Object>> queryHead(@RequestBody DepartClassParam param, HttpServletRequest request) {
            if (tokenService.compareToken(param.tokenEntity.getValue())) {
                String year = (String) request.getSession().getAttribute("currentYear");
                if(year==null)
                {
                    return ResultUtils.getResults(Result.Status.OVERTIME,"登录超时，请重新登录",null);
                }

                HashMap<String,Object> map = new HashMap<>();
                List<DepartClassHead> heads = headService.queryByDatetime(year);
                map.put("list",heads);
                map.put("datetime",year);
                return ResultUtils.getSuccessResults(map);
            }

        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对",null);
    }

    //添加单位分类
    @PostMapping("/beforeAddDepartClass")
    public  Result<HashMap<String,Object>> beforeAddDepartClass(@RequestBody DepartClassParam param,HttpServletRequest request)
    {
        if(tokenService.compareToken(param.tokenEntity.getValue()))
        {

            String year = (String) request.getSession().getAttribute("currentYear");
            if(year==null)
            {
                return ResultUtils.getResults(Result.Status.OVERTIME,"登录超时，请重新登录",null);
            }

            List<DepartClassHead> heads = headService.queryByDatetime(year);

            List<HashMap<String,Object>> listMap = new ArrayList<>();

            for (DepartClassHead head : heads) {
                HashMap<String,Object> map = new HashMap<>();
                map.put("weightName",head.getWeightName());
                map.put("headId",head.getId());
                map.put("weight",0);
                map.put("id",null);
                map.put("classId",null);
                listMap.add(map);
            }

            HashMap<String,Object> dataMap = new HashMap<>();
            dataMap.put("weightList",listMap);



            return ResultUtils.getSuccessResults(dataMap);
        }

        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对",null);
    }

    //添加单位分类
    @PostMapping("/addDepartClass")
    public  Result<HashMap<String,Object>> addDepartClass(@RequestBody DepartClassParam param,HttpServletRequest request)
    {
        if(tokenService.compareToken(param.tokenEntity.getValue()))
        {
            HashMap<String,Object> map = new HashMap<>();

            String str = dpclassService.saveDepartWeight(param.departClass);
            if(!"ok".equals(str))
            {
                return ResultUtils.getResults(Result.Status.ERROR, "操作失败",null);
            }


            return ResultUtils.getSuccessResults(map);
        }

        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对",null);
    }


    /**
     *   单位分类主查询入口
     * @param param
     * @param request
     * @return
     */
    @PostMapping("/queryDepartClass")
    public  Result<HashMap<String,Object>> queryDepartClass(@RequestBody DepartClassParam param,HttpServletRequest request)
    {
        if(tokenService.compareToken(param.tokenEntity.getValue()))
        {


            String year = (String) request.getSession().getAttribute("currentYear");
            if(year==null)
            {
                return ResultUtils.getResults(Result.Status.OVERTIME,"登录超时，请重新登录",null);
            }

             //HashMap<String,Object> map = new HashMap<>();
             //List<DepartClassHead> heads = headService.queryByDatetime(year);

            HashMap<String, Object> weight = dpclassService.getDepartWeight(year);

            //更新单位分类表头表
            // ；
            CountryUnitIndicatorsFilter filter = new CountryUnitIndicatorsFilter();
            filter.setDateTime(year);
            //取出县直单位所在年份所有指标
            List<CountryUnitIndicatorsEntity> query = uninService.query(filter);
            headService.updateDepartHead(query);


            return ResultUtils.getSuccessResults(weight);
        }

        return ResultUtils.getResults(Result.Status.OVERTIME, "token错误",null);
    }

    //修改权重
    @PostMapping("/BeforeUpdateWeight")
    public Result<String> updateDepartWeight(@RequestBody DepartClassParam param,HttpServletRequest request)
    {

        if(tokenService.compareToken(param.tokenEntity.getValue()))
        {
            String datetime = param.departClass.getDatetime();
            if(StringUtils.isBlank(datetime))
            {
                datetime = (String) request.getSession().getAttribute("currentYear");
                if(datetime==null)
                {
                    return ResultUtils.getResults(Result.Status.OVERTIME,"登录超时，请重新登录",null);
                }
            }
            itemService.updateOrSaveWeight(param.departClass);

            return ResultUtils.getSuccessResults();

        }

        return ResultUtils.getResults(Result.Status.OVERTIME, "token错误",null);
    }



}

class  DepartClassParam{
    public DepartClass departClass;
    public DepartClassFilter departClassFilter;
    public TokenEntity tokenEntity;
}